package com.example.feitou.photo_switching;

import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private ImageView img;
    private Button btnNext;
    private int[] images = {R.drawable.oldman1,R.drawable.oldman2,R.drawable.oldman3,R.drawable.oldman4,R.drawable.oldman5};
    private int index = 0;

    private Button btnAuto;
    private Handler handler;
    private final int CHANGE_IMG = 10001;
    private boolean isPause = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        img = findViewById(R.id.img);
        btnNext = findViewById(R.id.btn_next);
        btnAuto = findViewById(R.id.btn_auto);
        //初始化handler，响应子线程发出的消息
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                if(message.what == CHANGE_IMG){
                    index = (index+1)%images.length;
                    img.setImageResource(images[index]);
                }
                return false;
            }
        });



        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                    index = (index+1)%images.length;
                    img.setImageResource(images[index]);
            }
        });
        //新子线程，多线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                //while实现死循环
                while(true){
                    try {
                        Thread.sleep(1000);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    if(!isPause) {
                        Message message = new Message();
                        message.what = CHANGE_IMG;//int类型的消息
                        handler.sendMessage(message);//发送消息
                    }
                }

            }
        }).start();
        //快捷按钮alt+enter,new后面的是ctrl+shift+space
        btnAuto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                    isPause =! isPause;

            }
        });
    }
}
